<template>
  <Drawer ref="refDrawer" title="验证结果" @close="onClose">
    <div ref="refBoxLoading" class="relative mt-5">
      <StatusBoolean
        trueText="签名有效"
        falseText="签名无效"
        v-model="formData.verifyResult"
      >
        <template v-if="formData.verifyResult == false">
          <div
            @click="onLocate"
            class="text-primary flex-1 text-right cursor-pointer"
          >
            了解详情
          </div>
        </template>
      </StatusBoolean>

      <div class="box-info info1">
        <div class="title">电子签名信息</div>
        <div class="item-info" v-for="item in formData.signatureList">
          <div class="label">签章者：</div>
          <div>{{ item.signer }}</div>
          <div class="label">签章数量：</div>
          <div>{{ item.signCount }}个</div>
        </div>
      </div>
      <div class="box-info">
        <template v-if="formData.verifyResult === true">
          <div class="title">有效性总结</div>
          <ul>
            <li class="item-info">
              1. 符合《电子签名法》第十三条中可靠电子签名的规定。
            </li>
            <li class="item-info">2. 自签名人签署后，电子签名未被更改。</li>
            <li class="item-info">
              3. 自签名人签署后，由电子签名保护的文档内容未被更改。
            </li>
          </ul>
        </template>
        <template v-else-if="formData.verifyResult === false">
          <div class="title">无效性总结</div>
          <ul>
            <li
              class="item-info"
              v-for="(item, index) in formData.verifyResultRemark"
            >
              {{ index + 1 }}. {{ item }}
            </li>
          </ul>
        </template>
      </div>
    </div>
  </Drawer>
</template>
<script setup>
import { reactive, toRefs, ref } from "vue";
import _ from "lodash";
import { http, ss, loading, seal } from "@/utils";
import $ from "jquery";

const refDrawer = ref();
const refBoxLoading = ref();
const state = reactive({
  transactionId: "",
  style: {
    iconSize: 18,
    visible: false,
  },
  formData: {
    signatureList: [],
    verifyResult: null,
    verifyResultRemark: [],
  },
});
const { style, formData } = toRefs(state);

const onReset = () => {
  state.formData.verifyResult = null;
  state.formData.signatureList = [];
  state.formData.verifyResultRemark = [];
};

let timer2;
const getInfos = async () => {
  let timeStart = +new Date();
  loading.show({
    target: "#rightContainer",
  });
  const [err, res] = await http.post({
    data: {
      serviceCode: "verifyElectronicSealSignature",
      featureCode: "verifyFileElectronicSealSignature",
      businessData: {
        fileId: ss.get("fileId"),
      },
    },
  });
  if (res) {
    pollingStart(res.transactionId);
  } else {
    if (new Date() - timeStart < 500) {
      timer2 && clearTimeout(timer2);
      timer2 = setTimeout(() => {
        refDrawer.value.close();
        loading.close();
      }, 500);
    } else {
      refDrawer.value.close();
      loading.close();
    }
  }
};

let timer4;
const locateFirstUnPass = () => {
  let el = $(".item-signature.notpass")[0];
  if (el) {
    clearTimeout(timer4);
    el.scrollIntoView({ behavior: "smooth", block: "center" });
    el.click();
  } else {
    timer4 = setTimeout(() => {
      locateFirstUnPass();
    }, 500);
  }
};

const onLocate = () => {
  if (!$("#viewAttachments").hasClass("active")) {
    $("#viewAttachments").click();
  }
  locateFirstUnPass();
};

const onClose = () => {
  state.style.visible = false;
  clearTimeout(timer4);
  pollingStop();
};

let timer;
const pollingStop = () => {
  if (timer) {
    clearTimeout(timer);
  }
};

const pollingStart = transactionId => {
  const _doPoll = async () => {
    if (!state.style.visible) {
      //弹窗未展示时，停止执行
      return;
    }
    const [err, res] = await http.post({
      data: {
        serviceCode: "verifyElectronicSealSignature",
        featureCode: "getVerifyElectronicSealSignatureResult",
        businessData: {
          transactionId,
        },
      },
    });
    if (res) {
      let { verifyStatus } = res;
      if (verifyStatus == 10) {
        //10 验章进行中
        timer = setTimeout(_doPoll, 2000);
      } else if (verifyStatus == 20) {
        //20 验章已完成
        pollingStop();
        loading.close();
        state.formData.verifyResult = res.verifyResult;
        state.formData.signatureList = res.signatureList;
        state.formData.verifyResultRemark = res.verifyResultRemark;

        for (let [key, value] of Object.entries(
          res.signatureDomainIdAndStatusMap
        )) {
          provideHome.signatureValidateResult[
            seal.formatSignatureDomainId(key)
          ] = value;
        }
      }
    } else {
      pollingStop();
      loading.close();
    }
  };
  _doPoll();
};

defineExpose({
  show({} = {}) {
    refDrawer.value.show({});
    state.style.visible = true;
    onReset();
    setTimeout(() => {
      getInfos();
    });
  },
});
</script>
<style lang="scss" scoped>
.box-info {
  padding: 16px;
  margin-top: 16px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 4px;
  background: #f8f8f8;

  .label {
    @apply text-[#969AA0];
  }

  .title {
    color: #333;
    font-weight: 500;
    font-size: 14px;
    margin-bottom: 8px;
    @apply relative pl-[6px];
    &:before {
      content: "";
      @apply w-[2px]  h-[16px] absolute bg-[#165DFF] left-0 top-[2px];
    }
  }
  &.info1 {
    .item-info {
      display: grid;
      grid-template-columns: 64px 1fr;
      row-gap: 4px;
      border-bottom: solid 1px var(--el-border-color);
      padding: 4px 0;
      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>
